package server;

import codec.DataDecode;
import codec.DataEncode;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import server.handle.ServerInboundHandle;
import server.route.IRoute;
import server.route.impl.PollingRoute;
import server.support.IServerInfoMap;
import server.support.ServerInfoMap;
import util.BannerUtil;

import java.io.*;
import java.net.URL;

public class CenterServer {
    static Logger logger = LoggerFactory.getLogger(CenterServer.class);

    static public IRoute iRoute =new PollingRoute();


    NioEventLoopGroup wk;
    NioEventLoopGroup boss;
    ChannelFuture bind ;

    ServerBootstrap serverBootstrap;
    int port;
    int wkNthread;

    boolean isStart  =false;

    public CenterServer(int port, int wkNthread) {
        this.port = port;
        this.wkNthread = wkNthread;
    }


    public void init(){
        serverBootstrap = new ServerBootstrap();
        wk = new NioEventLoopGroup();
        boss = new NioEventLoopGroup(wkNthread);

        serverBootstrap.group(boss,wk).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<NioSocketChannel>() {
            protected void initChannel(NioSocketChannel ch) throws Exception {
                ch.pipeline().addLast(new DataEncode());
                ch.pipeline().addLast(new DataDecode());
                ch.pipeline().addLast(new ServerInboundHandle());
            }
        });

        logger.info("初始化完成...");
    }

    public synchronized void run(){
        if(isStart){
            logger.error("不可重复启动...");
            return;
        }
        if(serverBootstrap==null){
            BannerUtil.showBanner(this.getClass());
            logger.info("正在初始化启动器...");
            init();
        }
        try {
            serverBootstrap.bind(port).sync();
            logger.info("注册中心在端口{}启动成功...",port);
            isStart = true;
        }catch (Exception e){
            logger.error("启动错误...详细原因:{}",e.getMessage());
            e.printStackTrace();
            wk.shutdownGracefully();
            boss.shutdownGracefully();
        }
    }

    //测试注册中心
    public static void main(String[] args) {
        CenterServer centerServer = new CenterServer(33333,2);
        centerServer.run();
    }

}
